/**
 * 142. 环形链表 II
 * https://leetcode-cn.com/problems/linked-list-cycle-ii/
 */
public class Solutions_142 {
    public static void main(String[] args) {
        int[] arr = {3, 2, 0, -4};
        int pos = 1;  // output: {2}

//        int[] arr = {1, 2};
//        int pos = 0;  // output: {1}

//        int[] arr = {1};
//        int pos = -1;  // output: {null}

        ListNode head = MyLinkedListUtils.ArrayToListNode(arr, pos);
        ListNode result = detectCycle(head);
        System.out.println(result);
    }

    public static ListNode detectCycle(ListNode head) {
        // 1. 快慢指针找到是否有环
        ListNode slow = head, fast = head;
        while (true) {
            if (fast == null || fast.next == null) {
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                break;
            }
        }
        // 2. 说明有环，再定义一个指针，指向 head，与 slow 指针同时走，相遇时，即入环的节点
        fast = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }
}
